package com.dianrui.qiyouriding.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.BottomSheetDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.blankj.utilcode.util.SPUtils;
import com.dianrui.qiyouriding.Constant;
import com.dianrui.qiyouriding.R;
import com.dianrui.qiyouriding.alipay.PayResult;
import com.dianrui.qiyouriding.event.AlipayCouponEnd;
import com.dianrui.qiyouriding.event.CouponEnd;
import com.dianrui.qiyouriding.util.MyUtil;
import com.dianrui.qiyouriding.okhttp.OkHttpRequest;
import com.dianrui.qiyouriding.util.StringUtils;
import com.dianrui.qiyouriding.util.ToastUtil;
import com.dianrui.qiyouriding.util.Url;
import com.google.gson.JsonObject;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 活动专区(买优惠券)
 * @author Administrator
 */
public class WebviewBuyCouponActivity extends BaseActivity {
    private boolean isSuccess = false;
    private boolean isError = false;
    private LinearLayout ll_control_error;
    protected TextView showMoney;
    private String money;
    private String couponId;

    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.webview)
    WebView couponWebview;
    @BindView(R.id.buy_coupon_btn)
    Button buyCouponBtn;
    @BindView(R.id.act_progressbar)
    ProgressBar mProgressBar;
    @BindView(R.id.show_webview_layout)
    LinearLayout showWebviewLayout;


    @Override
    public int getContentViewId() {
        return R.layout.buy_coupon_webview;
    }

    @SuppressLint({"SetJavaScriptEnabled", "ClickableViewAccessibility"})
    @Override
    public void initView() {
        customInit(true,R.color.main_color);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        title.setText(getString(R.string.active_list));

        buyCouponBtn.setVisibility(View.GONE);
        couponWebview.post(new Runnable() {
            @Override
            public void run() {
                String areaId = "";
                String member_id = "";
                if (StringUtils.isEmpty(SPUtils.getInstance().getString("area_id"))) {
                    areaId = "0";
                } else {
                    areaId = SPUtils.getInstance().getString("area_id");
                }
                if (StringUtils.isEmpty(SPUtils.getInstance().getString("member_id"))) {
                    member_id = "";
                } else {
                    member_id = SPUtils.getInstance().getString("member_id");
                }
                couponWebview.loadUrl(Url.BASE_URL + Constant.my_activity_url + member_id+"&area_id="+areaId);
                WebSettings webSetting = couponWebview.getSettings();
                webSetting.setJavaScriptEnabled(true);//支持js
                webSetting.setUseWideViewPort(true);
                webSetting.setLoadWithOverviewMode(true);
                webSetting.setAppCacheEnabled(false);
                webSetting.setSupportZoom(true);
                webSetting.setBuiltInZoomControls(true);
                webSetting.setDisplayZoomControls(false);
                webSetting.setDomStorageEnabled(true);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    webSetting.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
                }
                couponWebview.setWebViewClient(new AreaWebClient());
            }
        });
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                couponWebview.removeView(couponWebview);
            }
        });
        ll_control_error = (LinearLayout) findViewById(R.id.ll_control_error);
        Button errorBtn=ll_control_error.findViewById(R.id.online_error_btn_retry);
        TextView errorTitle=ll_control_error.findViewById(R.id.title);
        ImageView backimg=ll_control_error.findViewById(R.id.back);
        errorTitle.setText("找不到网页");
        backimg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        errorBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ll_control_error.setVisibility(View.GONE);
                showWebviewLayout.setVisibility(View.VISIBLE);
                couponWebview.reload();
            }
        });
    }

    class AreaWebClient extends WebViewClient {
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (mProgressBar != null) {
                mProgressBar.setVisibility(View.GONE);
            }
            if (!isError) {
                isSuccess = true;
                //回调成功后的相关操作
                ll_control_error.setVisibility(View.GONE);
                showWebviewLayout.setVisibility(View.VISIBLE);
                couponWebview.setVisibility(View.VISIBLE);
            } else {
                isError = false;
                couponWebview.setVisibility(View.GONE);
                showWebviewLayout.setVisibility(View.GONE);
                ll_control_error.setVisibility(View.VISIBLE);
            }
        }



        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                return;
            }
            isError = true;
            isSuccess = false;
            //6.0以下执行
            couponWebview.setVisibility(View.GONE);
            showWebviewLayout.setVisibility(View.GONE);
            ll_control_error.setVisibility(View.VISIBLE);

        }


        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
            isError = true;
            isSuccess = false;
            //6.0以上执行
            couponWebview.setVisibility(View.GONE);
            showWebviewLayout.setVisibility(View.GONE);
            ll_control_error.setVisibility(View.VISIBLE);

        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {//二级网页跳转
            view.loadUrl(url);
            buyCouponBtn.setVisibility(View.VISIBLE);
            title.setText("卡券详情");
            Uri uri = Uri.parse(url);
            Log.e("lzy","得到的url是-------> " + uri);
            // 得到参数字符串
            String zpParams = uri.getEncodedQuery();
            Log.e("lzy","得到拼接的参数是-----> " + zpParams);
            if (!TextUtils.isEmpty(zpParams)) {
                try {
                    String[] parameter = URLDecoder.decode(zpParams.split("\\?")[0], "utf-8").split("&");
                    couponId=parameter[2].split("coupon_id=")[1];
                    money=parameter[3].split("money=")[1];
                    Log.e("该优惠券money是---->",money);
                    Log.e("该优惠券Id是---->",couponId);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }catch (ArrayIndexOutOfBoundsException e) {
                    e.printStackTrace();
                }
            }
            return true;
        }
    }


    @Override
    public void initData() {

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(CouponEnd couponEnd) {
        finish();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(AlipayCouponEnd alipayCouponEnd) {
        finish();
    }


    @OnClick({R.id.back, R.id.buy_coupon_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                if (couponWebview.canGoBack()) {
                    couponWebview.goBack();
                    buyCouponBtn.setVisibility(View.GONE);
                    title.setText(getString(R.string.active_list));
                }else {
                    finish();
                }
                break;

            case R.id.buy_coupon_btn:
                if (StringUtils.isEmpty(SPUtils.getInstance().getString("card"))) {
                    Intent intent = new Intent(WebviewBuyCouponActivity.this, AuthActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("isBackAuth", "1");
                    intent.putExtras(bundle);
                    startActivity(intent);
                } else {
                    createPayDialog(money,couponId);
                }
                break;
                default:
                    break;

        }
    }


    @SuppressLint("InflateParams")
    private void createPayDialog(final String money, final String couponId) {
        final BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(WebviewBuyCouponActivity.this);
        View view = LayoutInflater.from(WebviewBuyCouponActivity.this).inflate(R.layout.dialog_coupon_pay, null);
        Button pay = view.findViewById(R.id.pay);
        ImageView close = view.findViewById(R.id.close);
        LinearLayout clickBalance = view.findViewById(R.id.click_balance);
        LinearLayout clickZfb = view.findViewById(R.id.click_zfb);
        LinearLayout clickWx = view.findViewById(R.id.click_wx);
        showMoney = view.findViewById(R.id.show_dialog_money);
        final CheckBox cbBalance = view.findViewById(R.id.cb_balance);
        final CheckBox cbZfb = view.findViewById(R.id.cb_zfb);
        final CheckBox cbWx = view.findViewById(R.id.cb_wx);


        StringBuilder stringBuilder=new StringBuilder();
        stringBuilder.append("￥").append(money);
        showMoney.setText(stringBuilder.toString());

        clickZfb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cbZfb.setChecked(true);
                cbWx.setChecked(false);
            }
        });
        clickWx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cbZfb.setChecked(false);
                cbWx.setChecked(true);
            }
        });
        cbZfb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cbZfb.setChecked(true);
                cbWx.setChecked(false);
            }
        });

        cbWx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cbZfb.setChecked(false);
                cbWx.setChecked(true);
            }
        });
        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bottomSheetDialog.dismiss();
            }
        });

        pay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               if (cbWx.isChecked()) {
                    bottomSheetDialog.dismiss();
                   wxPays(money.replace("￥",""),couponId);
                }if (cbZfb.isChecked()) {
                    bottomSheetDialog.dismiss();
                    zfbPays(money.replace("￥",""),couponId);
                }
            }
        });
        bottomSheetDialog.setContentView(view);
        bottomSheetDialog.setCanceledOnTouchOutside(false);
        bottomSheetDialog.show();
    }

    private void wxPays(String money, String couponIds){
        JsonObject payJson =new JsonObject();
        if (!StringUtils.isEmpty(SPUtils.getInstance().getString("member_id"))) {
            payJson.addProperty("member_id", SPUtils.getInstance().getString("member_id"));
        }
        payJson.addProperty("payment_mode", "2");
        payJson.addProperty("money", money);
        payJson.addProperty("type", "5");
        payJson.addProperty("ids", couponIds);
        if (!StringUtils.isEmpty(SPUtils.getInstance().getString("area_id"))) {
            payJson.addProperty("area_id", SPUtils.getInstance().getString("area_id"));
        }
        OkHttpRequest.getInstance().postRequests(Url.PAY, payJson.toString(), new OkHttpRequest.XCallBack() {
            @Override
            public void onResponse(String response) {
                if (!StringUtils.isEmpty(response)) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        if (null!=jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.getString("status"))) {
                                IWXAPI msgApi = WXAPIFactory.createWXAPI(WebviewBuyCouponActivity.this, Constant.WXAppID, true);
                                if (!msgApi.isWXAppInstalled()) {
                                    ToastUtil.showToast(getString(R.string.wx_installed));
                                }
                                PayReq payReq = new PayReq();
                                payReq.appId = jsonObject.optJSONObject("data").optString("appid");
                                payReq.partnerId = jsonObject.optJSONObject("data").optString("partnerid");
                                payReq.prepayId = jsonObject.optJSONObject("data").optString("prepayid");
                                payReq.packageValue = jsonObject.optJSONObject("data").optString("package");
                                payReq.nonceStr = jsonObject.optJSONObject("data").optString("noncestr");
                                payReq.extData = "CouponPay";
                                payReq.timeStamp = jsonObject.optJSONObject("data").optString("timestamp");
                                payReq.sign = jsonObject.optJSONObject("data").optString("sign");
                                msgApi.sendReq(payReq);
                            } else {
                                ToastUtil.showToast(jsonObject.optString("message"));
                            }
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }



    private void zfbPays(String money, String couponIds){
        JsonObject payJson =new JsonObject();
        if (!StringUtils.isEmpty(SPUtils.getInstance().getString("member_id"))) {
            payJson.addProperty("member_id", SPUtils.getInstance().getString("member_id"));
        }
        payJson.addProperty("payment_mode", "3");
        payJson.addProperty("money", money);
        payJson.addProperty("type", "5");
        payJson.addProperty("ids", couponIds);
        if (!StringUtils.isEmpty(SPUtils.getInstance().getString("area_id"))) {
            payJson.addProperty("area_id", SPUtils.getInstance().getString("area_id"));
        }
        OkHttpRequest.getInstance().postRequests(Url.PAY, payJson.toString(), new OkHttpRequest.XCallBack() {
            @Override
            public void onResponse(String response) {
                if (!StringUtils.isEmpty(response)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(response);
                        if (null!=jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                if (!MyUtil.checkAliPayInstalled(WebviewBuyCouponActivity.this)) {
                                    ToastUtil.showToast(getString(R.string.zfb_installed));
                                    return;
                                }
                                Runnable payRunnable = new Runnable() {

                                    @Override
                                    public void run() {
                                        try {
                                            PayTask alipay = new PayTask(WebviewBuyCouponActivity.this);
                                            final Map<String, String> res = alipay.payV2(jsonObject.getJSONObject("data").optString("contents"), true);
                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    PayResult payResult = new PayResult(res);
                                                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                                                    String resultStatus = payResult.getResultStatus();
                                                    if ("9000".equals(resultStatus)) {
                                                        ToastUtil.showToast(getString(R.string.pay_success));
                                                    } else {
                                                        ToastUtil.showToast(getString(R.string.pay_failed));
                                                    }
                                                }
                                            });
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                };
                                Thread payThread = new Thread(payRunnable);
                                payThread.start();
                            } else {
                                ToastUtil.showToast(jsonObject.optString("message"));
                            }
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK && couponWebview.canGoBack()) {
                buyCouponBtn.setVisibility(View.GONE);
                couponWebview.goBack();
                title.setText(getString(R.string.active_list));
                return true;
            } else {
                onBackPressed();
            }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackPressed() {
        if (couponWebview.canGoBack()) {
            couponWebview.goBack();
            buyCouponBtn.setVisibility(View.GONE);
            title.setText(getString(R.string.active_list));
        }else {
            finish();
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (couponWebview != null) {
            couponWebview.onResume();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (couponWebview != null) {
            couponWebview.onPause();
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        couponWebview.destroy();
        couponWebview.clearHistory();
        couponWebview.removeAllViews();
        couponWebview.stopLoading();
        couponWebview.destroy();
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                ((ViewGroup) couponWebview.getParent()).removeView(couponWebview);
            }
        });

    }
}
